import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-10
 * Time: 21:13
 */
class producer_consumer_semaphore_Test{
    private static final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1000);
    private static final int capacity = 5;
    //未占用资源5个
    private static final Semaphore empty = new Semaphore(capacity);
    //已占用资源0个
    private static final Semaphore fill = new Semaphore(0);
    //实现互斥锁，非0即1
    private static final Semaphore mutex = new Semaphore(1);

    private static class producer implements Runnable {
        @Override
        public void run() {
            int n = 0;
            try {
                while (true) {
                    System.out.println("producer:" + ++n);
                    empty.acquire();
                    mutex.acquire();
                    queue.add(n);
                    mutex.release();
                    fill.release();
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                throw new RuntimeException(e);
            }
        }
    }
    private static class consumer implements Runnable{
        @Override
        public void run() {
            try {
                while (true) {
                    fill.acquire();
                    mutex.acquire();
                    System.out.println("consumer:" + queue.take());
                    mutex.release();
                    empty.release();
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                throw new RuntimeException(e);
            }
        }
    }
    public void start(){
        Thread ThreadProducer = new Thread(new producer());
        Thread ThreadConsumer = new Thread(new consumer());
        ThreadProducer.start();
        ThreadConsumer.start();
    }
}

public class Producer_Consumer_Semaphore {
    public static void main(String[] args) {
        producer_consumer_semaphore_Test producerConsumerSemaphore = new producer_consumer_semaphore_Test();
        producerConsumerSemaphore.start();
    }
}
